package com.example.cameralu.testdemotbsplus0522;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.Toast;

import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by Jacky F1233804 on 2018/7/9
 * desc：
 */

public class MyTBSWebView extends WebView {


    private AttributeSet attrs;
    private Context context;
    private boolean isReady = false;
    private static final String SETUP_HTML = "file:///android_asset/whatToEat.html";
    private static final String CALLBACK_SCHEME = "callback://";
    private static final String STATE_SCHEME = "state://";
    private String mContents;
//    private OnTextChangeListener mTextChangeListener;
//    private AfterInitialLoadListener mLoadListener;


    public MyTBSWebView(Context context) {
        this(context, null);
        this.context = context;

    }

    public MyTBSWebView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.webViewStyle);
        this.context = context;
        this.attrs = attrs;

    }

    public MyTBSWebView(Context context, AttributeSet attrs, int webViewStyle) {
        super(context, attrs, webViewStyle);
        this.context = context;
        this.attrs = attrs;
        init();
    }


    private void init() {
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        WebSettings webSettings = this.getSettings();
        //适配手机大小
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true);
        this.setWebChromeClient(new ChromeClient());
        this.setWebViewClient(new Client());

    }

    private class ChromeClient extends WebChromeClient {


        /**
         * 当页面中触发了alert(),confirm(),prompt()这三个方法，就会对应回调到下面三个方法中
         * 相当于js调用了安卓的方法，这也算是一种安卓和js的通信,
         * 复写了下面这3方法并且返回true就不会显示页面的弹窗了，而且一定要有确认或者取消的操作，不然会卡死
         * 但能拿到弹出里的所有信息，可以自己写原生弹窗等,如alert,toast等,很灵活
         *
         */
        @Override
        public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
            return super.onJsAlert(webView, s, s1, jsResult);
        }

        @Override
        public boolean onJsConfirm(WebView webView, String s, String s1, JsResult jsResult) {
            return super.onJsConfirm(webView, s, s1, jsResult);
        }


        @Override
        public boolean onJsPrompt(WebView webView, String s, String s1, String s2, JsPromptResult jsPromptResult) {
            return super.onJsPrompt(webView, s, s1, s2, jsPromptResult);
        }


    }


    private class Client extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {

            webView.loadUrl(url);
            if (getX5WebViewExtension() != null) {
                Toast.makeText(context, "x5 core", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "sys core", Toast.LENGTH_SHORT).show();

            }


            String decode;
            try {
                decode = URLDecoder.decode(url, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // No handling
                return false;
            }

            if (TextUtils.indexOf(url, CALLBACK_SCHEME) == 0) {
                callback(decode);
                return true;
            } else if (TextUtils.indexOf(url, STATE_SCHEME) == 0) {
                stateCheck(decode);
                return true;
            }

            return super.shouldOverrideUrlLoading(webView, url);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
            return super.shouldOverrideUrlLoading(webView, webResourceRequest);
        }


        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //https忽略证书问题
            handler.proceed();
        }


        @Override
        public void onPageFinished(WebView webView, String url) {
            isReady = url.equalsIgnoreCase(SETUP_HTML);
//            if (mLoadListener != null) {
//                mLoadListener.onAfterInitialLoad(isReady);
//            }
        }
    }


    public void loadURL(String url) {
        if (url.isEmpty()) {
            loadUrl(SETUP_HTML);
        } else {
            loadUrl(url);
        }
    }

    public interface AfterInitialLoadListener {

        void onAfterInitialLoad(boolean isReady);
    }


    public void showInfoFromJava(String msg) {
        exec("javascript:showInfoFromJava('" + msg + "')");
    }

    protected void exec(final String trigger) {
        if (isReady) {
            load(trigger);
        } else {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    exec(trigger);
                }
            }, 100);
        }
    }

    private void load(String trigger) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            evaluateJavascript(trigger, null);
        } else {
            loadUrl(trigger);
        }
    }


    private void callback(String text) {
        mContents = text.replaceFirst(CALLBACK_SCHEME, "");
//        if (mTextChangeListener != null) {
//            mTextChangeListener.onTextChange(mContents);
//        }
    }

    public interface OnTextChangeListener {

        void onTextChange(String text);
    }

    private void stateCheck(String text) {
//        String state = text.replaceFirst(STATE_SCHEME, "").toUpperCase(Locale.ENGLISH);
//        List<Type> types = new ArrayList<>();
//        for (Type type : Type.values()) {
//            if (TextUtils.indexOf(state, type.name()) != -1) {
//                types.add(type);
//            }
//        }
//
//        if (mDecorationStateListener != null) {
//            mDecorationStateListener.onStateChangeListener(state, types);
//        }
    }


}
